app.controller('userscontroller', ['$scope', '$parse', '$http', function($scope, $parse, $http)
{
	$scope.$on('translations', function(event, args) {
		$scope.translations = args.translations.response;
		$scope.getAllProfilesCommand();
	});
	
	function convertToPascalCase() {
		return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
	}
	
	function convertToLower() {
		return this.toLowerCase(); 
	}

	String.prototype.toLower = convertToLower;
	String.prototype.toPascalCase = convertToPascalCase;

	/**
	*	Get all active tasks
	*/
	$scope.getUsersCommand = function()
	{
		console.info("getUsersCommand - called"); 
		$scope.loadingUsers = true;

		$http.post($scope.servicebase, { "service" : "getUsers"}).
		success(function(data, status) 
		{
			console.info("getUsersCommand - call success"); 
			$scope.status = status;
			$scope.data = data;
			$scope.result = data; 
			$scope.loadingUsers = false;
			if(data.isFailed == true)
			{
				$scope.setMessageCommand($scope.data.exception, 'danger');
			}
			else
			{
				$scope.users = $scope.data.response;
			}
			$scope.canAddUser = true;
		})
		.
		error(function(data, status) 
		{
			console.error("getUsersCommand - call failed"); 	
			$scope.loadingUsers = false;
			$scope.data = data || "Request failed";
			$scope.status = status;			
			console.error("getUsersCommand - data : " + $scope.data); 				
		});
	};
	
	/**
	* Prepare to add a new user
	*/
	$scope.prepareAddUserCommand = function()
	{
		$scope.clearNewUserFormCommand();
		$("#addUser").modal('show');
	};
	
	/**
	* Prepare to edit the user
	*/
	$scope.prepareEditUserCommand = function(user)
	{
		console.info("Set all user informations");
		
		$scope.canUpdateUser = false;
		$scope.editUserId = user.Id;
		$scope.editFirstname = user.Firstname;
		$scope.editLastname = user.Lastname;
		$scope.editCompany = user.Company;
		$scope.editEmail = user.Email;
		$scope.editPhoneNumber = user.PhoneNumber;
		$scope.editWebAddress = user.WebAddress;
		$scope.editProfile = $scope.profiles[user.Profile];
		$scope.editLogin = user.Login;
		$scope.editUserHasAvatar = (user.Avatar == '') ? false : true;

		if($scope.editUserHasAvatar == true)
		{
			$scope.editUserAvatar = user.Avatar;
			$scope.editUserAvatarMime = user.AvatarMime;
		}

		$("#editUser").modal('show');
		$scope.canUpdateUser = true;
	};
	
	/**
	* Clear the new user form
	*/
	$scope.clearNewUserFormCommand = function()
	{
		console.info("clearNewUserFormCommand called");
		$scope.addFirstname= '';
		$scope.addLastname = '';
		$scope.addEmail = '';
		$scope.addPhoneNumber = '';
		$scope.addProfile = 0;
	};
	
	/**
	* Set an avatar on the event
	*/
	$scope.setAvatarCommand = function(file)
	{
		console.info("setAvatarCommand called ");
		$scope.Avatar = file;
	};
	
	/**
	* Attach a avatar on an user
	*/
	$scope.attachAvatarToUserCommand = function(idUser)
	{
		console.info("attachAvatarToUserCommand - called with id user : " + idUser);
		
		var fd = new FormData();
		fd.append("service", "attachAvatarOnAnUser");
		fd.append("idUser", idUser);
		fd.append("file", $scope.Avatar);
		
		$http.post($scope.servicebase,
			fd,
			{ 
				withCredentials: true, headers: {'Content-Type': undefined }, transformRequest: angular.identity 
			}
		).
		success(function(data, status) 
		{
			console.info("attachAvatarToUserCommand - call success"); 
			$scope.status = status;
			$scope.data = data;
			$scope.result = data;
			
			if(data.isFailed == true)
			{
				$scope.setMessageCommand(data.exception, 'warning');
			}
			else
			{
				$scope.setMessageCommand('Avatar joint.', 'success');
			}
			$scope.Avatar = undefined;
		})
		.
		error(function(data, status) 
		{
			console.error("attachAvatarToUserCommand - call failed"); 	
			$scope.setMessageCommand('Ajout d\'une affiche en échec.', 'danger');
			$scope.data = data || "Request failed";
			$scope.status = status;				
			console.error("attachAvatarToUserCommand - data : " + $scope.data);			
		});
	};
	
	/**
	* Set a new password for the user
	*/
	$scope.updateUserPasswordCommand = function()
	{
		console.info("updateUserPasswordCommand - called"); 
		$http.post($scope.servicebase, { "service" : "deleteMaterial", "id" : material.Id }).
		success(function(data, status) 
		{
			console.info("updateUserPasswordCommand - call success"); 
			$scope.status = status;
			$scope.data = data;
			$scope.result = data; 
			if(data.isFailed == true)
			{
				$scope.setMessageCommand($scope.data.exception, 'danger', 'messageUpdateUser');
			}
			else
			{
				$scope.messageUpdateUserVisible = true;
				$scope.setMessageCommand('Mot de passe regénéré', 'warning', 'messageUpdateUser');
			}
		})
		.
		error(function(data, status) 
		{
			console.error("updateUserPasswordCommand - call failed"); 	
			$scope.data = data || "Request failed";
			$scope.status = status;			
			console.error("updateUserPasswordCommand - data : " + $scope.data); 				
		});
	};
	
	/**
	* Prepare to edit the user
	*/
	$scope.updateUserCommand = function()
	{
		console.info("updateUserCommand - called"); 
		
		$scope.canUpdateUser = false;
		
		try
		{
			if($scope.editFirstname == "")
			{
				throw "Le prénom de l'utilisateur est obligatoire.";
			}
			
			if($scope.editLastname == "")
			{
				throw "Le nom de l'utilisateur est obligatoire.";
			}
			
			if($scope.editEmail == "")
			{
				throw "L'adresse mail de l'utilisateur est obligatoire.";
			}

			var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
			if(re.test($scope.editEmail) == false)
			{
				throw "L'adresse mail de l'utilisateur n'est pas valide.";
			}
			
			if($scope.editLogin == "")
			{
				throw "L'identifiant de l'utilisateur est obligatoire.";
			}
			
			$scope.editProfile = $scope.profiles.indexOf($scope.editProfile);
														
			$http.post($scope.servicebase, { "service" : "updateUser", "id" : $scope.editUserId, "firstname" : $scope.editFirstname.toPascalCase(), "lastname" : $scope.editLastname.toPascalCase(), "company" : $scope.editCompany.toPascalCase(), "email" : $scope.editEmail.toLower(), "phonenumber" : $scope.editPhoneNumber, "webaddress" : $scope.editWebAddress.toLower(), "login" : $scope.editLogin.toLower(), "profile" : $scope.editProfile }).
			success(function(data, status) 
			{
				console.info("updateUserCommand - call success"); 
				$scope.status = status;
				$scope.data = data;
				$scope.result = data; 
				
				if(data.isFailed == true)
				{
					$scope.setMessageCommand($scope.data.exception, 'danger', 'messageUpdateUser');
				}
				
				$("#editUser").modal('hide');
				$scope.getUsersCommand();
				$scope.canUpdateUser = true;
				$scope.setMessageCommand("L'utilisateur #" + $scope.editUserId + " a été mis à jour." , 'success');
				
				if($scope.Avatar != undefined)
				{
					$scope.attachAvatarToUserCommand($scope.editUserId);
				}
			})
			.
			error(function(data, status) 
			{
				console.error("updateUserCommand - call failed"); 	
				$scope.data = data || "Request failed";
				$scope.status = status;			
				$scope.canUpdateUser = true;
				console.error("updateUserCommand - data : " + $scope.data); 				
			});
		}
		catch(err) 
		{
			$scope.messageUpdateUserVisible = true;
			$scope.canUpdateUser = true;
			$scope.setMessageCommand(err, 'danger', 'messageUpdateUser');
		}
	};
			
	/**
	* Confirm to delete an user
	*/
	$scope.confirmDeleteUserCommand = function(user)
	{
		$scope.currentUser = user;
		$("#confirmDeleteUser").modal('show');
	};
	
	/**
	* Delete an user
	*/
	$scope.deleteUserCommand = function(user)
	{
		console.info("deleteUserCommand - called"); 
		$http.post($scope.servicebase, { "service" : "deleteUser", "id" : user.Id }).
		success(function(data, status) 
		{
			console.info("deleteUserCommand - call success"); 
			$scope.status = status;
			$scope.data = data;
			$scope.result = data; 
			if(data.isFailed == true)
			{
				$scope.setMessageCommand($scope.data.exception, 'danger');
			}
			var index = $scope.users.indexOf(user);
			if (index > -1) 
			{
				$scope.users.splice(index, 1);
			}
			$("#confirmDeleteUser").modal('hide');
		})
		.
		error(function(data, status) 
		{
			console.error("deleteUserCommand - call failed"); 	
			$scope.data = data || "Request failed";
			$scope.status = status;			
			console.error("deleteUserCommand - data : " + $scope.data); 				
		});
	};
	
	/**
	* Cancel the document deletion
	*/
	$scope.cancelDeleteUserCommand = function()
	{
		$("#confirmDeleteUser").modal('hide');
	};
	
	/**
	* Check all users states
	*/
	$scope.checkUsersStatesCommand = function ()
	{
		//console.info("checkUsersStatesCommand called");
		if($scope.users != undefined)
		{
			$http.post($scope.servicebase, { "service" : "getUsers"}).
			success(function(data, status) 
			{
				if(data.isFailed == false)
				{
					var toRefresh = false;
					if(data.response.length != $scope.users.length)
					{
						console.info("there is " + data.response.length + " users on database and " + $scope.users.length + " on local.");
						toRefresh = true;
					}
					else
					{
						//console.info("check all users " + $scope.users.length);
						$scope.users.forEach(function(user) {
							data.response.forEach(function(userFromResponse) {
								if(user.Id == userFromResponse.Id & user.State != userFromResponse.State)
								{
									console.info("user Id " + user.Id + " has change state from " + user.State + " to " + userFromResponse.State);
									toRefresh = true;
								}
							});
						});
					}
					
					if(toRefresh)
					{
						$scope.users = data.response;
					}
				}
			})
			.
			error(function(data, status) 
			{
				console.error("getUsers - call failed"); 	
			});
		}
	};
			
	/**
	* Add an user on database 
	*/
	$scope.addUserCommand = function()
	{
		console.info("addUserCommand - called"); 
		try
		{
			var profileIndex = $scope.profiles.indexOf($scope.addProfile);
		
			if(profileIndex == -1)
			{
				profileIndex = 0;
			}
			
			if($scope.addFirstname == "")
			{
				throw "Le prénom de l'utilisateur est obligatoire.";
			}
			
			if($scope.addLastname == "")
			{
				throw "Le nom de l'utilisateur est obligatoire.";
			}
			
			if($scope.addEmail == "")
			{
				throw "L'adresse mail de l'utilisateur est obligatoire.";
			}

			var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
			if(re.test($scope.addEmail) == false)
			{
				throw "L'adresse mail de l'utilisateur n'est pas valide.";
			}
			
			$http.post($scope.servicebase, { "service" : "addUser", "firstname" : $scope.addFirstname.toPascalCase(), "lastname" : $scope.addLastname.toPascalCase(), "company" : $scope.addCompany.toPascalCase(), "email" : $scope.addEmail.toLower(), "phonenumber" : $scope.addPhoneNumber, "webaddress" : $scope.addWebAddress.toLower(), "profile" : profileIndex }).
			success(function(data, status) 
			{
				alert(JSON.stringify(data));
				console.info("addUserCommand - call success"); 
				$scope.status = status;
				$scope.data = data;
				$scope.result = data; 
				if(data.isFailed == true)
				{
					$scope.setMessageCommand($scope.data.exception, 'danger');
				}
				else
				{
					$scope.users.push($scope.data.response);
					$scope.canAddUser = true;
					$("#addUser").modal('hide');
					$scope.setMessageCommand("Utilisateur ajouté avec succès.", 'success');
					if($scope.Avatar != undefined)
					{
						$scope.attachAvatarToUserCommand($scope.editUserId);
					}
				}
			})
			.
			error(function(data, status) 
			{
				console.error("addUserCommand - call failed"); 	
				$scope.canAddUser = true;
				$scope.data = data || "Request failed";
				$scope.status = status;			
				console.error("addUserCommand - data : " + $scope.data); 				
			});
		}
		catch(err)
		{
			$scope.messageAddUserVisible = true;
			$scope.setMessageCommand(err, 'danger', 'messageAddUser');
		}
	};
	
	/**
	* Get all profiles
	*/
	$scope.getAllProfilesCommand = function()
	{
		console.info("getAllProfilesCommand - called");
		$http.post($scope.servicebase, { "service" : "getProfiles"}).
		success(function(data, status) 
		{
			console.info("getAllProfilesCommand - call success"); 
			$scope.status = status;
			$scope.data = data;
			$scope.result = data;
			if($scope.data.isFailed == true)
			{
				$scope.setMessageCommand($scope.data.exception, 'danger');
			}
			else
			{
				for(var profile in $scope.data.response) {
				   $scope.profiles.push($scope.translations["Users_Profile_" + profile]);
				}
			}
		})
		.
		error(function(data, status) 
		{
			console.error("getAllProfilesCommand - call failed"); 	
			$scope.data = data || "Request failed";
			$scope.status = status;
			console.error("getAllProfilesCommand - data : " + $scope.data);		
		});
	};
	
	/**
	*	Load the admin component
	*/
	$scope.loadUsersComponentCommand = function() 
	{
		console.info("loadAdminComponentCommand - called");
		$scope.getUsersCommand();
	};
	
	$scope.loadUsersComponentCommand();
	
	/**
	* Check all users states each 1 seconds
	*/
	setInterval(function()
	{
		$scope.checkUsersStatesCommand();
	}, 2000);
	
}]);